﻿/// <reference path="vswd-ext_2.2.js" />
function calculateUnderTimeWindow(defaultsssid,defaultsensorid) {
    var pagesize = 100;
    var day = new Date();
    var today = day.getFullYear() + '-' + padLeft((day.getMonth() + 1).toString(),"0",2) + '-' + padLeft(day.getDate().toString(),"0",2);
    var yyday = addDays(day, -1);
    var yestoday = yyday.getFullYear() + '-' + padLeft((yyday.getMonth() + 1).toString(), "0", 2) + '-' + padLeft(yyday.getDate().toString(), "0", 2);
    var filterData = 0;
    
    var trackerstore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'HandlerSearchTrackerName'
        }),
        reader: new Ext.data.JsonReader({
            fields: ['trackname','snid'],
            root: "data"
        })
    });

    
    var trackNameCombo = new Ext.form.ComboBox({
        store: trackerstore,
        mode: 'local',
        displayField: 'trackname',
        width: 200,
        valueField: 'snid'
    });

    var cmbQuickTimer = new Ext.form.ComboBox({
        editable: false,
        forceSelection: true,
        disableKeyFilter: true,
        typeAhead: false,
        mode: 'local',
        triggerAction: 'all',
        width: 50,
        store: new Ext.data.ArrayStore({
            fields: [{ name: 'val', type: 'integer' }, 'text'],
            data: [[0, _Time_Today], [1, _Time_Yesterday], [2, _Time_7Days], [3, _Time_ThisMonth], [4, _Time_30Days]]
        }),
        displayField: 'text',
        width: 100,
        valueField: 'val'
    });

    cmbQuickTimer.setValue(0);

    var cmbSearchType = new Ext.form.ComboBox({
        editable: false,
        forceSelection: true,
        disableKeyFilter: true,
        typeAhead: false,
        mode: 'local',
        triggerAction: 'all',
        width: 50,
        store: new Ext.data.ArrayStore({
            fields: [{ name: 'val', type: 'integer' }, 'text'],
            data: [[0, _Chart_Detail_Data], [1, _Chart_Filter_Data]]
        }),
        displayField: 'text',
        width: 130,
        valueField: 'val'
    });

    cmbSearchType.setValue(0);
    cmbSearchType.addListener('select', function(obj, record, index) {
        filterData = index;
    });
    var cmbPageSize = new Ext.form.ComboBox({
        editable: false,
        forceSelection: true,
        disableKeyFilter: true,
        typeAhead: false,
        mode: 'local',
        triggerAction: 'all',
        width: 50,
        store: new Ext.data.ArrayStore({
            fields: [{ name: 'val', type: 'integer' }, { name: 'pagesize', type: 'integer'}],
            data: [[0, 100], [1, 200], [2, 500]]
        }),
        displayField: 'pagesize',
        width: 50,
        valueField: 'val'
    });

    cmbPageSize.setValue(0);

    cmbQuickTimer.addListener('select', function(obj, record, index) {
        var val = record.get('val');

        var day = new Date();
        var tmpbegintstr = today;
        var tmpendstr = today;
        if (val == 0) {
            tmpbegintstr = today;
            tmpendstr = today;
        }
        else if (val == 1) {
            tmpbegintstr = yestoday;
            tmpendstr = yestoday;
        }
        else if (val == 2) {
            var tmpd = addDays(day, -6);
            tmpbegintstr = tmpd.getFullYear() + '-' + padLeft((tmpd.getMonth() + 1).toString(), '0', 2) + '-' + padLeft(tmpd.getDate().toString(), '0', 2);
            tmpendstr = today;
        }
        else if (val == 3) {
            var tmpd = addDays(day, -6);
            tmpbegintstr = tmpd.getFullYear() + '-' + padLeft((tmpd.getMonth() + 1).toString(), '0', 2) + '-01';
            tmpendstr = today;
        }
        else if (val == 4) {
            var tmpd = addDays(day, -30);
            tmpbegintstr = tmpd.getFullYear() + '-' + padLeft((tmpd.getMonth() + 1).toString(), '0', 2) + '-' + padLeft(tmpd.getDate().toString(), '0', 2);
            tmpendstr = today;
        }
        fromDateEditor.setValue(tmpbegintstr);
        toDateEditor.setValue(tmpendstr);
        fromTimeEditor.setValue("00:00");
        toTimeEditor.setValue("23:59");
    });

    cmbPageSize.addListener('select', function(obj, record, index) {
        pagesize = record.get('pagesize');
        bbar.pageSize = pagesize;
    });

    var fromDateEditor = new Ext.form.DateField({
        renderer: Ext.util.Format.dateRenderer('Y-m-d'),
        format: 'Y-m-d',
        value: today
    });

    var fromTimeEditor = new Ext.form.TimeField({
        value:"00:00",
        format: 'H:i',
        width: 70
    });

    var toDateEditor = new Ext.form.DateField({
        renderer: Ext.util.Format.dateRenderer('Y-m-d'),
        format: 'Y-m-d',
        value: today
    });

    var toTimeEditor = new Ext.form.TimeField({
        value:'23:59',
        format: 'H:i',
        width: 70
    });

    var calculatedefinestore = new Ext.data.JsonStore({
        url: 'HandlerGetCalculateAndExtendSensorInfo',
        root: 'data',
        fields: [
        'Expression',
        'Calculate',
        'ShowType',
        {name:'Index',type:'integer'},
        {name:'SensorID',type:'integer'}
        ]
    });
    
    trackerstore.on('load',function(store,records){
        
        if(Ext.isDefined(defaultsssid)){
            trackNameCombo.setValue(defaultsssid);
            calculatedefinestore.reload({
                params:{
                    sssid:defaultsssid
                }
            });
        }else{
            calculatedefinestore.load();
        }
    });
    
    calculatedefinestore.on('load',function(store,records){
        store.each(function(record){
            if(record.get('Expression') == '01FF')
                record.set('Expression',_ConfigResource_Fuel);
            if(record.get('Expression') == 'S_S_1')
                record.set('Expression',_ConfigResource_Fuel);
            if(record.get('Expression') == 'S_S_2')
                record.set('Expression',_ConfigResource_Fuel);
        });
        if(Ext.isDefined(defaultsensorid)){
            calculateCombo.setValue(defaultsensorid);
            _selectedSensorRecord= calculatedefinestore.getAt(calculatedefinestore.findExact('Index',defaultsensorid));
        }
    });
    
    var calculateCombo = new Ext.form.ComboBox({
        name: 'calculateComboValue',
        store: calculatedefinestore,
        mode: 'local',
        displayField: 'Expression',
        width: 130,
        valueField: 'Index',
        hiddenName: 'calculateComboValue',
        editable: false,
        triggerAction: 'all'
    });
    
    var _selectedSensorRecord ;
    calculateCombo.on('select',function(combo,record,index){
        _selectedSensorRecord = record;
    });
    
    trackNameCombo.on('select',function(combo,record,index){
        calculatedefinestore.reload({
            params:{
                sssid:record.get('snid')
            }
        });
    });
    
    trackNameCombo.on('afterrender',function(obj,layout){
        trackerstore.load();
    });
    
    var fields = ['Time', 'Value'];
    
    var historystore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: "HandlerGetCalculateHistory",
            method: "POST",
            timeout: 90000
        }),
        reader: new Ext.data.JsonReader({
            fields: fields,
            root: "data",
            totalProperty: "totalCount"
        })
    });
    
    var tbar = new Ext.Toolbar({
        items: [_Alarm_TrackerName+':',
        trackNameCombo,
        {
            xtype: 'tbseparator', width: 5
        }, calculateCombo,
        {
            xtype: 'tbseparator', width: 5
        },
        cmbQuickTimer,
        _Alarm_FromTime+':',
        fromDateEditor,
        {
            xtype: 'tbseparator', width: 5
        },
        fromTimeEditor,
        {
            xtype: 'tbseparator', width: 5
        },
        _Alarm_ToTime+':',
        toDateEditor,
        {
            xtype: 'tbseparator', width: 5
        },
        toTimeEditor,
        //{xtype:'tbfill'},
        cmbSearchType,
        cmbPageSize,
        {
        tooltip: { text: _TrackerMain_Search, autoHide: true },        
        icon: 'Content/images/search16.gif',
        handler: function() {
            if (trackNameCombo.getRawValue() != '' && calculateCombo.getRawValue() != '') {
                var store = calculateCombo.getStore();
                historystore.reload({
                    params: {
                        trackName: trackNameCombo.getRawValue(),
                        fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
                        totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
                        start: 0,
                        limit: pagesize,
                        filterData: filterData,
                        calculate: _selectedSensorRecord.get('Calculate'),
                        type: _selectedSensorRecord.get('ShowType'),
                        TableID: _selectedSensorRecord.get('SensorID'),
                        Index:_selectedSensorRecord.get('Index')
                    }
                });
            }
            else {
                Ext.Msg.alert(_Alarm_NoData, _Alarm_NoData);
            }

        }
}]
    });
    historystore.addListener('load', function(store, records) {
        Ext.MessageBox.show({
            msg: _CustomerConfigResource_Loading,
            progressText: _CustomerConfigResource_Loading,
            width: 300,
            wait: true,
            waitConfig: { interval: 2000 }
        });
        var i;
        if (records.length > 0) {
            Ext.MessageBox.hide();
            for (i = 0; i < records.length; i++) {
                var valid = records[i].get("gpsavailable");
                if (valid)
                    records[i].set("gpsexpression", _TrackerMain_Valid);
                else
                    records[i].set("gpsexpression", _TrackerMain_Invalid);
            }
        }
        else {

            Ext.MessageBox.hide();
            Ext.Msg.alert(_Alarm_NoData, _Alarm_NoData);
        }
    });



    var calculateUnderTimePanel = new Ext.Panel({
        width: 952,
        height: 402,
        title: _CustomerConfigResource_CalculateChart,
        layout: 'fit',
        items: {
            store: historystore,
            xtype: 'linechart',
            xField: 'Time',
            yField: 'Value',
            tipRenderer: function(chart, record) {
                var calculateStore = calculateCombo.getStore();
                if(_selectedSensorRecord.get('Index') <0x100)
                {
                    var v = calculateCombo.getValue();
                    var r = calculateCombo.findRecord(calculateCombo.valueField || calculateCombo.displayField, v);
                    var index = calculateCombo.store.indexOf(r);
                    if (calculateStore.data.items[index].data.ShowType == _CustomerConfigResource_Decimal)
                        return _CustomerConfigResource_Time+':' + record.data.Time + _CustomerConfigResource_Value+':' + record.data.Value.toFixed(2);
                    else {
                        return _CustomerConfigResource_Time+':' + record.data.Time + _CustomerConfigResource_Value+':' + record.data.Value.toFixed(2) + "%";
                    }
                }
                else if(_selectedSensorRecord.get('Index') == 0x01FF){
                    return _CustomerConfigResource_Time+':' + record.data.Time + _CustomerConfigResource_Value+':' + record.data.Value.toFixed(2) + "%";
                }
                else{
                    
                    return _CustomerConfigResource_Time+':' + record.data.Time + _CustomerConfigResource_Value+':' + record.data.Value.toFixed(2);
                }
            }
        }
    });
    
    var bbar = new Ext.PagingToolbar({
            pageSize: pagesize,
            store: historystore,
            beforePageText: _Alarm_Page,
            refreshTex: _Alarm_Refresh,
            displayMsg: _Alarm_Displaying,
            emptyMsg: _Alarm_Alarm_emptyMsg,
            displayInfo: true
        });

    var calculateUnderTimeWindow = new Ext.Window({
        title: _CustomerConfigResource_CalculateChart,
        height: 490,
        width: 1200,
        items: calculateUnderTimePanel,
        tbar: tbar,
        iconCls:'chart-calculate',
        closeAction: 'hide',
        minimizable: true,
        layout: 'fit',
        constrain:true,
        listeners: {
            'minimize': function() {
                addTaskButtonForWindow(calculateUnderTimeWindow);
            }
        },
        bbar: bbar 
    });
    historystore.on('beforeload', function(store) {
        Ext.MessageBox.show({
            msg: _CustomerConfigResource_Loading,
            progressText: _CustomerConfigResource_Loading,
            width: 300,
            wait: true,
            waitConfig: { interval: 2000 }
        });
        var store1 = calculateCombo.getStore();
        historystore.baseParams = {   
            start: 'start', 
            limit: 'limit', trackName: trackNameCombo.getRawValue(), 
            fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value, 
            totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value, 
            calculate: _selectedSensorRecord.get('Calculate'),
            type: _selectedSensorRecord.get('ShowType'),
            TableID: _selectedSensorRecord.get('SensorID'),
            Index:_selectedSensorRecord.get('Index')
        }

    })
    
    calculateUnderTimeWindow.show();
    
    
};



function speedUnderTimeWindow() {
    var pagesize = 100;
    var filterData= 0;
    var day = new Date();
    var today = day.getFullYear() + '-' + padLeft((day.getMonth() + 1).toString(), "0", 2) + '-' + padLeft(day.getDate().toString(), "0", 2);
    var yyday = addDays(day, -1);
    var yestoday = yyday.getFullYear() + '-' + padLeft((yyday.getMonth() + 1).toString(), "0", 2) + '-' + padLeft(yyday.getDate().toString(), "0", 2);

    //load trackname
    var trackerstore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'HandlerSearchTrackerName'
        }),
        reader: new Ext.data.JsonReader({
            fields: ['trackname','snid'],
            root: "data"
        })
    });

    trackerstore.load()
    var trackNameCombo = new Ext.form.ComboBox({
        store: trackerstore,
        mode: 'local',
        displayField: 'trackname',
        width: 200,
        valueField: 'trackname'
    });

    var fromDateEditor = new Ext.form.DateField({
        renderer: Ext.util.Format.dateRenderer('Y-m-d'),
        format: 'Y-m-d',
        value: today
    });

    var fromTimeEditor = new Ext.form.TimeField({
        value:"00:00",
        format: 'H:i',
        width: 70
    });

    var toDateEditor = new Ext.form.DateField({
        renderer: Ext.util.Format.dateRenderer('Y-m-d'),
        format: 'Y-m-d',
        value: today
    });

    var toTimeEditor = new Ext.form.TimeField({
        value:'23:59',
        format: 'H:i',
        width: 70
    });

    var fields = ['gpstime', 'speed'];

    var historystore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: "HandlerSearchHistory",
            method: "POST",
            timeout:90000
        }),
        reader: new Ext.data.JsonReader({
            fields: fields,
            root: "data",
            totalProperty: "totalCount"
        })
    });
    
    var speedCompareData = [['0', '>='], ['1', '<=']];

    var speedCompareStore = new Ext.data.ArrayStore({
        fields: ['cmdid', 'text'],
        data: speedCompareData
    });

    var speedCompareEditor = new Ext.form.ComboBox({
        editable: false,
        disableKeyFilter: true,
        typeAhead: false,
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        store: speedCompareStore,
        displayField: 'text',
        width: 50,
        valueField: 'text'
    });

    var cmbQuickTimer = new Ext.form.ComboBox({
        editable: false,
        forceSelection: true,
        disableKeyFilter: true,
        typeAhead: false,
        mode: 'local',
        triggerAction: 'all',
        width: 50,
        store: new Ext.data.ArrayStore({
            fields: [{ name: 'val', type: 'integer' }, 'text'],
            data: [[0, _Time_Today], [1, _Time_Yesterday], [2, _Time_7Days], [3, _Time_ThisMonth], [4, _Time_30Days]]
        }),
        displayField: 'text',
        width: 100,
        valueField: 'val'
    });

    cmbQuickTimer.setValue(0);

    var cmbSearchType = new Ext.form.ComboBox({
        editable: false,
        forceSelection: true,
        disableKeyFilter: true,
        typeAhead: false,
        mode: 'local',
        triggerAction: 'all',
        width: 50,
        store: new Ext.data.ArrayStore({
            fields: [{ name: 'val', type: 'integer' }, 'text'],
            data: [[0, _Chart_Detail_Data], [1, _Chart_Filter_Data]]
        }),
        displayField: 'text',
        width: 130,
        valueField: 'val'
    });

    cmbSearchType.setValue(0);
    cmbSearchType.addListener('select',function(obj,record,index){
        filterData = index;
    });
    
    var cmbPageSize = new Ext.form.ComboBox({
        editable: false,
        forceSelection: true,
        disableKeyFilter: true,
        typeAhead: false,
        mode: 'local',
        triggerAction: 'all',
        width: 50,
        store: new Ext.data.ArrayStore({
            fields: [{ name: 'val', type: 'integer' }, { name: 'pagesize', type: 'integer'}],
            data: [[0, 100], [1, 200],[2,500]]
        }),
        displayField: 'pagesize',
        width: 50,
        valueField: 'val'
    });

    cmbPageSize.setValue(0);

    cmbQuickTimer.addListener('select', function(obj, record, index) {
        var val = record.get('val');

        var day = new Date();
        var tmpbegintstr = today;
        var tmpendstr = today;
        if (val == 0) {
            tmpbegintstr = today;
            tmpendstr = today;
        }
        else if (val == 1) {
            tmpbegintstr = yestoday;
            tmpendstr = yestoday;
        }
        else if (val == 2) {
            var tmpd = addDays(day, -6);
            tmpbegintstr = tmpd.getFullYear() + '-' + padLeft((tmpd.getMonth() + 1).toString(),'0',2) + '-' + padLeft(tmpd.getDate().toString(),'0',2);
            tmpendstr = today;
        }
        else if (val == 3) {
            var tmpd = addDays(day, -6);
            tmpbegintstr = tmpd.getFullYear() + '-' + padLeft((tmpd.getMonth() + 1).toString(), '0', 2) + '-01';
            tmpendstr = today;
        }
        else if (val == 4) {
            var tmpd = addDays(day, -30);
            tmpbegintstr = tmpd.getFullYear() + '-' + padLeft((tmpd.getMonth() + 1).toString(), '0', 2) + '-' + padLeft(tmpd.getDate().toString(),'0',2);
            tmpendstr = today;
        }
        fromDateEditor.setValue(tmpbegintstr);
        toDateEditor.setValue(tmpendstr);
        fromTimeEditor.setValue("00:00");
        toTimeEditor.setValue("23:59");
    });

    cmbPageSize.addListener('select', function(obj, record, index) {
        pagesize = record.get('pagesize');
        bbar.pageSize = pagesize;
    });
    
    speedCompareEditor.setValue('>=');

    var speedNumberEditor = new Ext.form.NumberField({
        width: 30,
        value: '0',
        allowBlank: false,
        blankText: _Message_BlankText,
        maxValue: 2000,
        minValue: 0,
        minText: _Message_MinText + ' 0',
        maxText: _Message_MaxText + ' 2000'
    });
    
    var tbar = new Ext.Toolbar({
        items: [_Alarm_TrackerName+':',
        trackNameCombo,
        {
            xtype: 'tbseparator', width: 5
        },
        cmbQuickTimer,
        _Alarm_FromTime+':',
        fromDateEditor,
        {
            xtype: 'tbseparator', width: 5
        },
        fromTimeEditor,
        {
            xtype: 'tbseparator', width: 5
        },
        _Alarm_ToTime+':',
        toDateEditor,
        {
            xtype: 'tbseparator', width: 5
        },
        toTimeEditor,
        _TrackerMain_Speed + ':',
        speedCompareEditor,
        speedNumberEditor,
        cmbSearchType,
        cmbPageSize,
        //{xtype:'tbfill'},
        {
        tooltip: { tooltip: { text: _TrackerMain_Search, autoHide: true }, autoHide: true },
        icon: 'Content/images/search16.gif',
        handler: function() {
            historystore.reload({
                params: {
                    trackName: trackNameCombo.getRawValue(),
                    fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
                    totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
                    start: 0,
                    limit: pagesize,
                    filterSamedata: 1,
                    filterData:filterData,
                    speedCompare: speedCompareEditor.getRawValue(),
                    speedNumber: speedNumberEditor.getRawValue()
                }
            });

        }
}]
    });
    historystore.addListener('load', function(store, records) {
        var i;
        Ext.MessageBox.hide();
        if (records.length > 0) {
            for (i = 0; i < records.length; i++) {
                records[i].set("gpstime", records[i].get("gpstime") + "    ");
                if (showmiles) {
                    records[i].set("speed", kilos2miles(records[i].get("speed")));
                }
            }
        }
        else {
            Ext.Msg.alert(_Alarm_NoData, _Alarm_NoData);
        }
    });

    var speedUnderTimePanel = new Ext.Panel({
        width: 935,
        height: 402,
        title: _TrackerMain_SpeedTimeReport,
        layout: 'fit',
        items: {
            store: historystore,
            xtype: 'linechart',
            xField: 'gpstime',
            yField: 'speed',
            tipRenderer: function(chart, record) {

            return _CustomerConfigResource_Time + ':' + record.data.gpstime + _CustomerConfigResource_Value + ':' + Ext.util.Format.number(record.data.speed, '0,0');

            }
        }
    });

    var bbar = new Ext.PagingToolbar({
        pageSize: pagesize,
        store: historystore,
        beforePageText: _Alarm_Page,
        refreshTex: _Alarm_Refresh,
        displayMsg: _Alarm_Displaying,
        emptyMsg: _Alarm_Alarm_emptyMsg,
        displayInfo: true
    });
    var speedUnderTimeWindow = new Ext.Window({
        title: _TrackerMain_SpeedTimeReport,
        height: 490,
        width: 1200,
        layout: 'fit',
        items: speedUnderTimePanel,
        tbar: tbar,
        closeAction: 'hide',
        iconCls: 'chart-speed',
        minimizable: true,
        constrain:true,
        listeners: {
            'minimize': function() {
                addTaskButtonForWindow(speedUnderTimeWindow);
            }
        },
        bbar: bbar
    });
    
    
    historystore.on('beforeload', function(store) {
        Ext.MessageBox.show({
            msg: _CustomerConfigResource_Loading,
            progressText: _CustomerConfigResource_Loading,
            width: 300,
            wait: true,
            waitConfig: { interval: 2000 }
        });
        historystore.baseParams = {
            start: 'start',
            limit: 'limit',
            trackName: trackNameCombo.getRawValue(),
            fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
            totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
            filterSamedata: 1,
            filterData: filterData,
            speedCompare: speedCompareEditor.getRawValue(),
            speedNumber: speedNumberEditor.getRawValue() 
        }
    })
    speedUnderTimeWindow.show();
};


